package main

import (
	"encoding/json"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"net/url"
	"qqRead/logger"
	"qqRead/pie"
	"strings"
)

// 清洗目录信息
// 清洗目录信息
func clearTocInfo(tocInfo string) (string, error) {
	var tocObject []Chapter
	err := json.Unmarshal([]byte(tocInfo), &tocObject)
	if err != nil {
		return "", err
	}
	var tocInfoStr string
	tmpLenth := len(tocObject)
	if len(tocObject) > 0 {

		for i, chapter := range tocObject {
			if (i + 1) == tmpLenth {
				tocInfoStr += string(chapter.Title)
			} else {
				tocInfoStr += string(chapter.Title) + "||"
			}
		}

		return tocInfoStr, nil
	}
	return "", nil
}

// 从分享URL提取bid
func extractBIDFromShareURL(shareURL string) string {
	// 解析URL
	parsedURL, err := url.Parse(shareURL)
	if err != nil {
		fmt.Printf("URL解析失败: %v\n", err)
		return ""
	}

	// 获取查询参数
	queryParams := parsedURL.Query()
	bid := queryParams.Get("bid")
	if bid == "" {
		fmt.Println("分享URL中未找到bid参数")
		return ""
	}

	return bid
}

// 获取书籍信息
func getBookInfo(url string) (*BookInfo, error) {
	// 创建自定义HTTP客户端并设置User-Agent
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP请求失败: %d %s", resp.StatusCode, resp.Status)
	}

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, err
	}

	info := &BookInfo{}

	// 提取书籍标题
	title := doc.Find(".book-title").Text()
	title = strings.ReplaceAll(title, " ", "")
	title = strings.ReplaceAll(title, "\n", "")
	info.Title = title

	// 提取作者信息
	authorSection := doc.Find(".author")
	if authorSection.Length() > 0 {
		author := strings.TrimSpace(authorSection.Text())
		author = strings.ReplaceAll(author, "\n", "")
		author = strings.ReplaceAll(author, " 著", "")
		info.Author = author
	} else {
		info.Author = "未知作者"
	}

	// 提取封面URL
	coverImg := doc.Find(".book-cover img")
	if coverImg.Length() > 0 {
		if src, exists := coverImg.Attr("src"); exists {
			src = strings.ReplaceAll(src, "/t5_", "/t9_")
			info.Cover = src
		}
	}

	// 提取字数信息
	if updateDate := doc.Find(".update-time"); updateDate.Length() > 0 {
		updateText := updateDate.Text()
		updateText = strings.ReplaceAll(updateText, "更新时间：", "")
		info.UpdateDate = updateText
	}

	// 提取状态信息
	if status := doc.Find(".free.vip"); status.Length() > 0 {
		info.Status = status.Text()
	} else if free := doc.Find(".free"); free.Length() > 0 {
		info.Status = free.Text()
	}

	// 提取书籍描述
	if intro := doc.Find(".book-intro"); intro.Length() > 0 {
		info.Description = strings.TrimSpace(intro.Text())
	}

	// 提取标签
	doc.Find(".tag").Each(func(i int, s *goquery.Selection) {
		tag := s.Text()
		tag = strings.ReplaceAll(tag, "\n", "")
		tag = strings.ReplaceAll(tag, " ", "")
		info.Tags = append(info.Tags, tag)
	})

	// 提取评分
	//if rating := doc.Find(".open-vip").Prev().Prev(); rating.Length() > 0 {
	//	info.Rating = rating.Text()
	//} else if ratingLabel := doc.Find(".label-rating"); ratingLabel.Length() > 0 {
	//	info.Rating = strings.TrimSpace(ratingLabel.Text())
	//}

	return info, nil
}

// 获取目录信息
func getChapters(url string) ([]Chapter, error) {
	// 创建自定义HTTP客户端并设置User-Agent
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP请求失败: %d %s", resp.StatusCode, resp.Status)
	}

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, err
	}

	var chapters []Chapter

	// 尝试查找目录区域
	var dirSection *goquery.Selection
	doc.Find(".book-dir").Each(func(i int, s *goquery.Selection) {
		if style, exists := s.Attr("style"); exists && strings.Contains(style, "display:none") {
			// 跳过隐藏的元素
			return
		}
		// 我们找到第一个非隐藏的.book-dir元素
		if dirSection == nil {
			dirSection = s
		}
	})

	if dirSection.Length() == 0 {
		// 如果没有找到.book-dir，尝试其他可能的类名
		dirSection = doc.Find(".dir-mod")
	}

	if dirSection.Length() > 0 {
		// 查找所有章节
		dirSection.Find(".list a").Each(func(_ int, item *goquery.Selection) {
			title := item.Find(".name").Text()
			href, exists := item.Attr("href")

			if title != "" && exists {
				// 确保URL完整
				fullURL := href
				if !strings.HasPrefix(href, "http") {
					fullURL = "https://book.qq.com" + href
				}

				chapters = append(chapters, Chapter{
					Title: title,
					URL:   fullURL,
				})
			}
		})
	}

	return chapters, nil
}

// 保存为JSON文件
func saveJSON(logg logger.Logger, cache *pie.FileCache, data interface{}, filename string) {
	jsonData, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		logg.Infof("JSON编码失败: %v\n", err)
		return
	}

	//err = ioutil.WriteFile(filename, jsonData, 0644)
	//if err != nil {
	//	fmt.Printf("文件保存失败: %v\n", err)
	//	return
	//}

	if err := cache.Set(filename, jsonData); err != nil {
		logg.Infof("Failed to set cache: %v\n", err)
	}

}
